package com.hevs.samplewebapp.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;

import com.google.appengine.api.datastore.Key;
import com.hevs.samplewebapp.server.entities.User;
import com.hevs.samplewebapp.server.json.ObjectMapperFactory;
import com.hevs.samplewebapp.server.service.UserService;

/**
 * 
 * @author Arnaud Durand creation : 22.03.12
 * 
 *         Goal: RESTful service for granting and revoking access to other
 *         users' data
 * 
 */
public class GrantingServlet extends SessionAuthHttpServlet {

	public GrantingServlet() {
		super(1);
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 9058798969131970668L;

	public static UserService userService;
	{
		userService = new UserService();
	};

	@Override
	protected void doSecureGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		HttpSession session = req.getSession(false);
		User user=new User();
		user.setKey((Key)session.getAttribute("userKey"));

		resp.setContentType("application/json");
		PrintWriter writer = resp.getWriter();

		ObjectMapper mapper = ObjectMapperFactory.get();
		writer.write(mapper.writeValueAsString(userService.getGrantedUsers(user)));

		writer.flush();
	}

	//grant
	@Override
	protected void doSecurePost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		HttpSession session = req.getSession(false);
		User user=new User();
		user.setKey((Key)session.getAttribute("userKey"));
		
			// getting remote user from post json content
			BufferedReader reader = req.getReader();
			StringBuilder sb = new StringBuilder();
			String line = reader.readLine();
			while (line != null) {
				sb.append(line + "\n");
				line = reader.readLine();
			}
			reader.close();
			System.out.println(sb.toString());

			ObjectMapper mapper = ObjectMapperFactory.get();
			User remote = mapper.readValue(sb.toString(), User.class);
			remote = userService.getUserByMail(remote.getEmail());
			
			if (remote == null || remote.getKey() == null) {
				resp.sendError(400);
				return;
			}
			//only doctors can be granted
			if (remote.getCredentialLevel()!=2){
				System.out.println("remote credentialLevel: "+remote.getCredentialLevel());
				resp.sendError(403);
				return;
			}
			

			
			userService.grantAccess(user, remote);
		
	}
	
	//revoke
	@Override
	protected void doSecureDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		

		HttpSession session = req.getSession(false);
		User user=new User();
		user.setKey((Key)session.getAttribute("userKey"));
		
			// getting remote user from post json content
			BufferedReader reader = req.getReader();
			StringBuilder sb = new StringBuilder();
			String line = reader.readLine();
			while (line != null) {
				sb.append(line + "\n");
				line = reader.readLine();
			}
			reader.close();
			System.out.println(sb.toString());

			ObjectMapper mapper = ObjectMapperFactory.get();
			User remote = mapper.readValue(sb.toString(), User.class);

			remote = userService.getUserByMail(remote.getEmail());
			
			// throw Error 400
			if (remote == null || remote.getKey() == null) {
				resp.sendError(400);
				return;
			}
			
			
			userService.revokeAccess(user, remote);

		
	}

	

}
